package ngat.oss;

import ngat.message.OSS.*;
import ngat.util.logging.*;
import ngat.phase2.*; 
import ngat.instrument.*;
import ngat.phase2.nonpersist.*;

import java.util.*;
import java.io.*;

import jyd.dbms.*;
import jyd.storable.*;
import jyd.collection.*;

/**
 * Action: Sent to retreive the entire DB tree description.
 * @author S.N.Fraser
 */
public class GET_TREEImpl extends TransactionImpl {

    /** Create a GET_TREEImpl for the specified request.*/
    public GET_TREEImpl(GET_TREE request) {
	super(request);
    }

    /**
     * Retrieves the Tree description.
     */
    public TRANSACTION_DONE exec() { 
	
	Root     root     = null;
	Tag      tag      = null;
	User     user     = null;
	Proposal proposal = null;

	Transaction t = null;
	try {
	    t = Transaction.current();
	    
	    root = OSS_Utilities.fetchRoot();
	    
	    // Check it exists.
	    if (root == null) {
		logger.log(1, CLASS, id, "exec", "Root: "+" Not in database.");
		return error(TRANSACTION.PATH_RESOLUTION_ERROR, 
				     "Could not find Root:");
	    } 
	    root.getName();

	    ItemDescriptor rootDesc = new ItemDescriptor(new String("root"));
	    
	    // Iterate round the Root's Tags.
	    Iterator it = root.listAllTags();
	    
	    while (it.hasNext()) {
		
		tag = (Tag)it.next();

		if (tag != null) {

		    tag.getName();
		    ItemDescriptor tagDesc = new ItemDescriptor(tag.getDescriptor());
		    rootDesc.add(tagDesc);

		    // Iterate round the Tag's Users.
		    Iterator iu = tag.listAllUsers();
	    
		    while (iu.hasNext()) {

			user = (User)iu.next();

			if (user != null) {

			    user.getName();
			    ItemDescriptor userDesc = new ItemDescriptor(user.getDescriptor());
			    tagDesc.add(userDesc);
			    
			     // Iterate round the User's Proposals
			    Iterator ip = user.listAllProposals();
			    
			    while (ip.hasNext()) {
				
				KVPair pair = (KVPair)ip.next();
				String name = (String)pair.getKey();

				try {
				    proposal = OSS_Utilities.fetchProposal(new Path(user.getFullPath(), name));
				    if (proposal != null) { 
					
					proposal.getName();
					ItemDescriptor proposalDesc = new ItemDescriptor(proposal.getDescriptor());
					userDesc.add(proposalDesc);

				    }
				} catch (IOException iox) {
				    logger.log(1, CLASS, id, "exec",
					       "Proposal: "+name+
					       " Error fetching from Database: "+iox);
				}			    
			    }			    
			}			
		    }		    
		}	
	    }	    
	    
	    GET_TREE_DONE done = new GET_TREE_DONE(id); 
	    done.setSuccessful(true);
	    done.setTreeDescriptor(rootDesc);
	    return done;	    	
  	    
	} finally {
	    t.commit();
	}	
    }
    
} // Class Def. [GET_TREEImpl].



